//
//  ICMProxyActivity.m
//  ICrEAM
//
//  Created by rainimute on 16/11/22.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "ICMProxyActivity.h"
#import "ICMProxyActivityModel.h"

@interface ICMProxyActivity ()<UITableViewDelegate,UITableViewDataSource,ICMProxyActivityCellDelegate>

@property (nonatomic, strong) NSMutableArray *selectedIndexs;

@property (nonatomic, strong) NSMutableArray *rotarionIndexs;

@end



@implementation ICMProxyActivity
- (instancetype)initSelecteActivityViewWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        self.activityTableView.hidden = NO;
        self.selectedIndexs = [NSMutableArray array];
        self.rotarionIndexs = [NSMutableArray array];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(proxyActivityLabourChanged:) name:@"proxyActivityLabourChanged" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(proxyActivityPartChanged:) name:@"ProxyActivityPartChanged" object:nil];
    }
    return self;
}

#pragma mark 初始化被选择的活动
- (void)resetSelectedActivity
{
    for(int i = 0;i<self.activityModels.count;i++)
    {
        ICMProxyActivityViewModel *model = self.activityModels[i];
        if([model.IS_CHECKED isEqualToString:ICMEnumIntToString(ICMEnumYESOrNOYES)])
        {
            [self.selectedIndexs addObject:[@(i) stringValue]];
        }
    }
}

+ (instancetype)createSelecteActivityViewWithFrame:(CGRect)frame{
    return [[ICMProxyActivity alloc]initSelecteActivityViewWithFrame:frame];
}

/*tableViewDelegate tableViewDataSource*/
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.activityModels.count;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ICMProxyActivityCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ICMSelecteActivityCell"];
    if (!cell) {
        cell = [[ICMProxyActivityCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ICMSelecteActivityCell"];
    }
    cell.delegate = self;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell setupSelecteActivityCellWithModel:self.activityModels[indexPath.row] WithExistDic:self.labourAndPartsExistDic];
    return cell;
}

#pragma mark 项目变化回调方法
- (void)proxyActivityLabourChanged:(NSNotification *)notification
{
    NSDictionary *dic = notification.userInfo;
    NSNumber *isSelected = dic[@"IsSelected"];
    if([isSelected boolValue])
    {
        if (![self.repairTypes containsObject:@"服务活动"]) {
            [self.repairTypes addObject:@"服务活动"];
            if ([self.delegate respondsToSelector:@selector(haveChangeRepairTypes)]) {
                [self.delegate haveChangeRepairTypes];
            }
        }
    }
}

#pragma mark 零件变化回调方法
- (void)proxyActivityPartChanged:(NSNotification *)notification
{
    NSDictionary *dic = notification.userInfo;
    NSNumber *isSelected = dic[@"IsSelected"];
    if([isSelected boolValue])
    {
        if (![self.repairTypes containsObject:@"服务活动"]) {
            [self.repairTypes addObject:@"服务活动"];
            if ([self.delegate respondsToSelector:@selector(haveChangeRepairTypes)]) {
                [self.delegate haveChangeRepairTypes];
            }
        }
    }
}

#pragma mark 选择活动回调方法
- (void)didSelectedCell:(ICMProxyActivityCell *)cell{
    self.hasViewValueChanged = YES;
    NSIndexPath *indexPath = [self.activityTableView indexPathForCell:cell];
    
    ICMProxyActivityViewModel *viewModel = self.activityModels[indexPath.row];
    viewModel.isSelected = !cell.subContentView.stateButton.selected;
    viewModel.IS_CHECKED = viewModel.isSelected?ICMEnumIntToString(ICMEnumYESOrNOYES):ICMEnumIntToString(ICMEnumYESOrNONO);
    BOOL isHaveSelected = NO;
    for (ICMProxyActivityViewModel *viewModelTemp in self.activityModels) {
        if (viewModelTemp.isSelected) {
            isHaveSelected = YES;
        }
    }
    
    [self.selectedIndexs containsObject:[@(indexPath.row) stringValue]]?[self.selectedIndexs removeObject:[@(indexPath.row) stringValue]]:[self.selectedIndexs addObject:[@(indexPath.row) stringValue]];
    dispatch_main_async_safe(^{
        [self.activityTableView reloadData];
    });
}

#pragma mark 点击展开按钮回调方法
- (void)didSelectedCellRotateButton:(ICMProxyActivityCell *)cell{
    NSIndexPath *indexPath = [self.activityTableView indexPathForCell:cell];
    ICMProxyActivityViewModel *viewModel = self.activityModels[indexPath.row];
    viewModel.isRotation = !cell.subContentView.rotateButton.selected;
    [self.rotarionIndexs containsObject:[@(indexPath.row) stringValue]]?[self.rotarionIndexs removeObject:[@(indexPath.row) stringValue]]:[self.rotarionIndexs addObject:[@(indexPath.row) stringValue]];
    dispatch_main_async_safe(^{
        [self.activityTableView reloadData];
    });
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    ICMProxyActivityViewModel *viewModel = self.activityModels[indexPath.row];
    if (!viewModel.isRotation) {
        return ActualHeight(100);
    }
    
    NSInteger labourCount = viewModel.allActivityModel.TT_ACTIVITY_LABOUR.count;
    NSInteger lineCount = (labourCount%3==0)?(labourCount/3):(labourCount/3+1);
    NSInteger partsCount = viewModel.allActivityModel.TT_ACTIVITY_PART.count;
    lineCount += (partsCount%3==0)?(partsCount/3):(partsCount/3+1);
//    if (partsCount == 0) {
//        lineCount --;
//    }
    
    return (lineCount+1)*ActualHeight(100);
    
}

- (UITableView *)activityTableView{
    if (!_activityTableView) {
        _activityTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
        _activityTableView.delegate = self;
        _activityTableView.dataSource = self;
        _activityTableView.backgroundColor = BackgroundColor_White;
        [_activityTableView registerClass:[ICMProxyActivityCell class] forCellReuseIdentifier:@"ICMSelecteActivityCell"];
        _activityTableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 1)];
        _activityTableView.tableFooterView.backgroundColor = [UIColor whiteColor];
        _activityTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self addSubview:_activityTableView];
    }
    return _activityTableView;
}

- (NSMutableArray *)activityModels{
    if (!_activityModels) {
        _activityModels = [NSMutableArray array];
    }
    return _activityModels;
}

- (void)setupSelecteActivityViewWithActivityModel:(ICMProxyActivityModel *)activityModel{
    //    self.selectedIndexs
    self.selectedIndexs = [NSMutableArray array];
    
    dispatch_main_async_safe(^{
        [self.activityTableView reloadData];
    });
}

- (NSMutableArray *)selectedActivitys{
    _selectedActivitys = [NSMutableArray array];
    for (NSString *index in self.selectedIndexs) {
        ICMProxyActivityViewModel *viewModel = self.activityModels[[index integerValue]];
        [_selectedActivitys addObject:viewModel];
    }
    return _selectedActivitys;
}

#pragma 页面值变化
- (void)setHasViewValueChanged:(BOOL)hasViewValueChanged
{
    _hasViewValueChanged = hasViewValueChanged;
    if(_hasViewValueChanged)
    {
        //发送变化通知
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ViewValueChanged" object:self];
    }
}

@end


/*ICMSelecteActivityCell*/

@interface ICMProxyActivityCell ()<ICMCellContentViewDelegate>


@end

@implementation ICMProxyActivityCell

#pragma mark 设置cell的内容
- (void)setupSelecteActivityCellWithModel:(ICMProxyActivityViewModel*)model WithExistDic:(NSMutableDictionary *)dic{
    self.labourAndPartsExistDic = dic;
    self.viewModel = model;
    [self.subContentView setupCellContentViewWithProxyActivityViewModel:model];
    
    self.subContentView.stateButton.selected = [model.IS_CHECKED isEqualToString:ICMEnumIntToString(ICMEnumYESOrNOYES)]?YES:NO;// model.isSelected;
    
    //IS_CHECKED 活动不被选中不能选择项目和零件
    if(self.subContentView.stateButton.selected)
    {
        self.subContentView.rotateButton.enabled = YES;
    }
    else
    {
        self.subContentView.rotateButton.enabled = NO;
    }
    
    self.subContentView.rotateButton.selected = model.isRotation;
    
    if(![self canCancelActivityWithDic:dic WithActCode:model.subTitle])
    {
        self.subContentView.stateButton.userInteractionEnabled = NO;
    }
    else
    {
        self.subContentView.stateButton.userInteractionEnabled = YES;
    }
    
    NSInteger labourCount = self.viewModel.allActivityModel.TT_ACTIVITY_LABOUR.count;
    NSInteger labourLineCount = (labourCount%3==0)?(labourCount/3):(labourCount/3+1);
    
    NSInteger partsCount = self.viewModel.allActivityModel.TT_ACTIVITY_PART.count;
    NSInteger partsLineCount = (partsCount%3==0)?(partsCount/3):(partsCount/3+1);
    
    self.labourView.frame = CGRectMake(0, ActualHeight(100), ScreenWidth, ActualHeight(100)*labourLineCount);
    
    self.partView.frame = CGRectMake(0, ActualWidth(100)*(labourLineCount+1), ScreenWidth, ActualHeight(100)*partsLineCount);
    
    self.partView.hidden = !model.isRotation;
    self.labourView.hidden = !model.isRotation;
    
}

#pragma mark 点击选择按钮回调方法
- (void)didSelected{
    if ([self.delegate respondsToSelector:@selector(didSelectedCell:)]) {
        [self.delegate didSelectedCell:self];
    }
}

#pragma mark 点击展开按钮回调方法
- (void)didSelectedRotateButton{
    if ([self.delegate respondsToSelector:@selector(didSelectedCellRotateButton:)]) {
        [self.delegate didSelectedCellRotateButton:self];
    }
}

- (ICMCellContentView *)subContentView{
    if (!_subContentView) {
        _subContentView = [ICMCellContentView createCellContentViewWithProxyActivityViewModel:self.viewModel andFrame:CGRectMake(0, 0, ScreenWidth, ActualHeight(100))];
        _subContentView.delegate = self;
        [self.contentView addSubview:_subContentView];
    }
    return _subContentView;
}

- (ICMCellPartView *)partView{
    if (!_partView) {
        _partView = [ICMCellPartView createCellPartViewWithViewModel:self.viewModel];
        
        NSInteger labourCount = self.viewModel.allActivityModel.TT_ACTIVITY_LABOUR.count;
        NSInteger labourLineCount = (labourCount%3==0)?(labourCount/3):(labourCount/3+1);
        
        NSInteger partsCount = self.viewModel.allActivityModel.TT_ACTIVITY_PART.count;
        NSInteger partsLineCount = (partsCount%3==0)?(partsCount/3):(partsCount/3+1);
        
        _partView.frame = CGRectMake(0, ActualWidth(100)*(labourLineCount+1), ScreenWidth, ActualHeight(100)*partsLineCount);
        [self.contentView addSubview:_partView];
    }
    [_partView setupCellPartViewWithViewModel:self.viewModel WithExistDic:self.labourAndPartsExistDic];
    return _partView;
}

- (ICMCellLabourView *)labourView{
    if (!_labourView) {
        _labourView = [ICMCellLabourView createCellLaourViewWithViewModel:self.viewModel];
        NSInteger labourCount = self.viewModel.allActivityModel.TT_ACTIVITY_LABOUR.count;
        NSInteger labourLineCount = (labourCount%3==0)?(labourCount/3):(labourCount/3+1);
        
        _labourView.frame = CGRectMake(0, ActualHeight(100), ScreenWidth, ActualHeight(100)*labourLineCount);
        [self.contentView addSubview:_labourView];
    }
    [_labourView setupCellPartViewWithViewModel:self.viewModel WithExistDic:self.labourAndPartsExistDic];
    return _labourView;
}


#pragma mark 根据选择dic 查找这个活动是否可取消 存在选择的项目和零件时不能取消活动
- (BOOL)canCancelActivityWithDic:(NSMutableDictionary *)dic WithActCode:(NSString *)actCode
{
    NSMutableDictionary *dic1 = [dic objectForKey:actCode];
    NSMutableDictionary *dic2 = [dic1 objectForKey:@"PANLabour"];
    NSMutableDictionary *dic3 = [dic1 objectForKey:@"PANParts"];
    //检查项目
    for(NSString *labourKey in dic2.allKeys)
    {
        NSNumber *labourNum = [dic2 objectForKey:labourKey];
        if([labourNum boolValue] == YES)
        {
            return NO;
        }
    }
    //检查零件
    for(NSString *partKey in dic3.allKeys)
    {
        NSNumber *partNum = [dic3 objectForKey:partKey];
        if([partNum boolValue] == YES)
        {
            return NO;
        }
    }
    return YES;
}

@end













